<template>
  <div class="app-container">
    <comprehensive-table
            @selection-change="selectionChange"
            :columns="column" :data="data" @reset="reset" @onSubmit="onSubmit" >
      <template v-slot:btn>
       <div style="display: flex;justify-content: flex-end">
         <el-button type="primary" @click="add"><el-icon><plus /></el-icon> 添加</el-button>
         <el-button type="danger" @click="batchDelete"><el-icon><delete /></el-icon>删除</el-button>
       </div>
      </template>
      <!-- <template v-slot:sex="scope">{{scope.row.sex?'男':'女'}}</template> -->
      <template v-slot:operation="scope">
        <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="edit(scope.row)"
        >
          编辑
        </el-button>
        <el-button
            @click="del(scope.row)"
            type="danger"
            size="small"
            icon="Delete"
        >
          删除
        </el-button>
				<el-button
				    @click="revise(scope)"
				    :type="scope.row.state? 'danger': 'success'"
				    size="small"
				    icon="Delete"
				>
				  {{scope.row.state ? '禁用' : '启用'}}
				</el-button>
				
      </template>
			
    </comprehensive-table>

    <el-dialog
        :visible.sync="dialogVisible"
            :title="title"
            width="50%"
    >
      <el-form
              ref="ruleFormRef"
              :model="ruleForm"
              :rules="rules"
              label-width="120px"
              class="demo-ruleForm"
              :size="formSize"
      >
        <el-form-item label="用户名" prop="name">
				  <el-input v-model="ruleForm.name" />
				</el-form-item>
				<el-form-item label="身份" prop="roleId">
				  <el-select v-model="ruleForm.roleId" placeholder="身份">
				    <el-option label="管理员" value="管理员"></el-option>
				    <el-option label="普通用户" value="普通用户"></el-option>
						<el-option label="vip用户" value="vip用户"></el-option>
						<el-option label="员工" value="员工"></el-option>
				  </el-select>
				</el-form-item>
				<el-form-item label="上传图片" prop="avatar">
				  <el-upload
				      class="upload-demo"
				      action="/upload"
				      :on-success="handleUploadSuccess"
				      :before-upload="beforeUpload"
				      :on-remove="handleRemove"
				    >
				    <el-button size="small" type="primary">点击上传</el-button>
				  </el-upload>
				</el-form-item>
				
				<el-form-item label="积分" prop="integral">
				  <el-input v-model="ruleForm.integral" type="number"/>
				</el-form-item>
				<el-form-item label="性别" prop="sex" >
				  <el-select v-model="ruleForm.sex" placeholder="请选择性别">
				    <el-option label="男"  value="男"></el-option>
				    <el-option label="女" value="女"></el-option>
				  </el-select>
				</el-form-item>
				<el-form-item label="电话" prop="phone">
				  <el-input v-model="ruleForm.phone" />
				</el-form-item>
				<el-form-item label="邮箱Email" prop="email">
				  <el-input v-model="ruleForm.email" />
				</el-form-item>
      </el-form>
			
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleClose('ruleFormRef')"
        >确定</el-button
        >
      </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
var dayjs = require('dayjs')
  import ComprehensiveTable from './components/comprehensive.vue'
	import axios from 'axios'
	
  const data = []
  // for(let i=0;i<100;i++){
  //   data.push({
  //     date: '2016-05-02',
  //     name: '王五'+i,
  //     types: '纸品类',
		// 	store:'五华区121大街店',
		// 	orderNum:'0120352145' + i ,
  //     admin:"admin",
  //     checked:true,
  //     id:i+1,
  //     age:0,
  //     remark:'早点来',
  //     address: '上海市普上海',
  //     zip: 200333,
		// 	weight:'10-20kg',
		// 	price:'100',
			
  //   })
  // }
  const column = [
		{type:'selection', width:60 },
		{name:'id', label: 'id',inSearch:true, valueType:'input',width:60, },
		{name:'name', label: '用户名',		width:140},
		{name:'roleId', label: '身份',inSearch:true, valueType:'input',width:80, },
		{name:'avatar', label: '头像',width:130,},
	  {name:'stateText', label: '账号状态', inSearch:true, valueType:'input', width:100 },
		{name:'sex', label: '性别', width:60 },
		{name:'integral', label: '积分',		width:80},
		{name:'phone', label: '电话',	inSearch:true,	valueType:'input',	width:150},
		{name:'email', label: '邮箱Email',		width:200},
    {name:'operation',slot:true,fixed:'right',width:230 }
  ]
  export default {
    components:{
      ComprehensiveTable
    },
    data(){
      return{
        data,
        column,
        formSize:'default',
        ruleForm:{
          name: '',
					roleId:'普通用户',
					avatar:'null',
					integral:0,
					stateText:'',
					sex:'',
          phone:'',
					email:'',
					
        },
        rules:{
					roleId: [
					 {  message: '请选择一个选项', trigger: 'change' }
					],
					avatar: [
					  {  message: '请上传头像', trigger: 'change' }
					],
					integral: [
					 {required: true, message: '请输入数字', trigger: 'blur' }
					],
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
            { min: 1, max: 9, message: '名字不能超过9位', trigger: 'blur' },
          ],
          sex: [
            {required: true,message: '请选择性别',trigger: 'change',},
          ],
					phone: [
						{ required: true, message: '手机号码不能为空', trigger: 'blur' },
						{ pattern: /^\d{11}$/, message: '手机号码必须为11位数字', trigger: 'blur' }
          ],
					email: [
					  { message: '邮箱不能为空', trigger: 'blur' },
					  { pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: '邮箱格式不正确', trigger: 'blur' }
					],
        },
        dialogVisible:false,
        title:'新增',
        rowObj:{},
        selectObj:[],
				// 分页查询
				currentPage: 1,
				pageSize: 10,
				totalPages: 1,
      }
    },
		created() {
		  this.fetchData();
		},
    methods:{
			fetchData() {
	      axios.get('http://43.136.172.73/api/v1/admin/page', {
	        params: {
	          page: 1,
	          pageSize:100000,
	        },
					headers:{
						Authorization:''
					}
	      })
	      .then(response => {
	        this.data = response.data.data.records;
					this.data.map(item=>{
					
						item.roleId = item.roleId == 0 ? "管理员" :(item.roleId == 1 ? "普通用户" :(item.roleId == 2 ? "vip用户" : (item.roleId == 3 ? "员工" : '')));
						item.sex = item.sex ? "男" : "女" ;	
						item.stateText = item.state ? '正常':'封禁中'
					})
					// this.$eventBus.$emit('total-updated', this.total);
	        // this.totalPages = responseData.totalPages;
	      })
	      .catch(error => {
	        console.error('Error:', error);
	      });
	    },
	    // prevPage() {
	    //   if (this.currentPage > 1) {
	    //     this.currentPage--;
	    //     this.fetchData();
	    //   }
	    // },
	    // nextPage() {
	    //   if (this.currentPage < this.totalPages) {
	    //     this.currentPage++;
	    //     this.fetchData();
	    //   }
	    // },
      async handleClose(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (valid) {
              let obj = {
                // id:Date.now(),
                ...this.ruleForm,
              }
							console.log(obj);
							
              if(this.title==='新增'){
                this.data = [obj,...this.data]
								console.log(obj.roleId);
								obj.state = true ;
								obj.roleId = obj.roleId == "管理员" ? 0 :(obj.roleId == "普通用户" ? 1 :(obj.roleId == "vip用户" ? 2 : (obj.roleId == "员工" ? 3 : '3')));
								obj.sex = obj.sex == "男" ? 1 : 0 ;
								console.log(obj);
								setTimeout(() => {
								axios.post('http://43.136.172.73/api/v1/admin',{
										sex: obj.sex,
										state: obj.state,
										name: obj.name,
										avatar: obj.avatar,
										integral: obj.integral,
										email: obj.email,
										phone: obj.phone,
										roleId: obj.roleId,
									},{
										headers:{
											Authorization:''
										},
									}).then(response => {
										console.log(response.data); // 处理响应结果
									})
									.catch(error => {
										console.error(error); // 处理请求错误
										this.$message.success('添加成功')
									})},500)
                this.fetchData();
              }else {
								console.log(this.data);
                this.data.forEach(item=>{
                  if(item.id===this.rowObj.id){
                    item.name=obj.name
                    item.sex=obj.sex
                    item.roleId=obj.roleId
										item.integral=obj.integral
										item.phone=obj.phone
										item.email=obj.email
                  }
								
                })
								obj.roleId = obj.roleId == "管理员" ? 0 :(obj.roleId == "普通用户" ? 1 :(obj.roleId == "vip用户" ? 2 : (obj.roleId == "员工" ? 3 : '3')));
								obj.sex = obj.sex == "男" ? 1 : 0 ;
								obj.integral=parseInt(obj.integral) 
								obj.roleId=parseInt(obj.roleId) 
								console.log("obj" , obj);
								const data = {
									bodyData: {
									  name: obj.name,
								    integral: obj.integral,
										sex:obj.sex,
										id:this.rowObj.id,
										email:obj.email,
										roleId:obj.roleId,
										avatar:obj.avatar,
										phone:obj.phone  
									}
								    
								  };
								setTimeout(() => {
									axios.put('http://43.136.172.73/api/v1/admin/update', {
										name: obj.name,
										integral: obj.integral,
										sex:obj.sex,
										id:this.rowObj.id,
										email:obj.email,
										roleId:obj.roleId,
										avatar:obj.avatar,
										phone:obj.phone 
									},{
										headers:{
											Authorization:''
										}
								})
								  .then(response => {
								    console.log(response);
										this.$message.success('修改成功')
										this.fetchData();
								  })
								  .catch(error => {
								    console.error(error);
								  })},1000)
              }
              this.dialogVisible = false
							
              console.log('submit!',obj)
            } else {
              console.log('error submit!', fields)
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      add(){
        this.title='新增'
        this.dialogVisible = true
      },
      batchDelete(val){
				console.log(val);
        if(!this.selectObj.length){
          return this.$message.error('未选中任何行')
        }
        this.$confirm(
            '你确定要删除选中项吗?',
            '温馨提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
              draggable: true,
            }
        )
            .then(() => {
              this.$message.success('模拟删除成功')
              this.data = this.data.concat([])
            })
            .catch(() => {

            })
      },
      selectionChange(val){
        this.selectObj = val
      },
      edit(row){
        this.title='编辑'
        this.rowObj = row
        this.dialogVisible = true
        this.ruleForm.name = row.name
				this.ruleForm.roleId = row.roleId
				this.ruleForm.integral = row.integral
				this.ruleForm.sex = row.sex 
				this.ruleForm.phone = row.phone
				this.ruleForm.email = row.email
				
				console.log(row);
				
      },
      del(row){
        this.$confirm(
            '你确定要删除当前项吗?',
            '温馨提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
              draggable: true,
            }
        )
            .then(() => {
							console.log(row.id);
							const idArray = [];
							idArray.push(row.id);
							console.log(idArray);
							const url = 'http://43.136.172.73/api/v1/admin/deletes';
							const headers = {Authorization:'dsa'}
							setTimeout(() => {
								axios.delete(url, {
								  data: idArray, // 将idArray作为请求体数据
								  headers: {
								    Authorization:'dsa' 
								  },
								}).then(response => {
							    // 处理成功响应
									console.log(response);
									this.$message.success('删除成功')
									this.fetchData()
							  })
							  .catch(error => {
							    // 处理错误
							  })
								},1000)
              
            })
            .catch(() => {

            })
      },
			revise(scope){
				if(scope.row.state == true){
					this.$confirm(
				    '你确定要封禁该账号吗?',
				    '温馨提示',
				    {
				      confirmButtonText: '确定',
				      cancelButtonText: '取消',
				      type: 'warning',
				    })
				    .then(() => {
							setTimeout(() => {
							axios.put('http://43.136.172.73/api/v1/admin/state',null,  {
							  params: {
							    userId: scope.row.id,
							    status: "false"
							  },
								headers:{
									Authorization:''
								}
							})
							  .then(response => {
									console.log(scope);
							    console.log(response.data);
									this.$message.success('启用成功')
									this.fetchData();
							  })
							  .catch(error => {
							    console.error(error);
							  })},1000);
				      
				    })
				    .catch(() => {
				
				    })
				}else{
					this.$confirm(
					  '你确定要启用该账号吗?',
					  '温馨提示',
					  {
					    confirmButtonText: '确定',
					    cancelButtonText: '取消',
					    type: 'warning',
					    draggable: true,
					  })
					  .then(() => {
						setTimeout(() => {
							axios.put('http://43.136.172.73/api/v1/admin/state', null, {
							  params: {
							    userId: scope.row.id,
							    status: "true"
							  },
								headers:{
									Authorization:''
								}
							})
							  .then(response => {
									this.$message.success('启用成功')
									this.fetchData();
							  })
							  .catch(error => {
							    console.error(error);
							  })},2000);
					    
					  })
					  .catch(() => {
									
					  })
				}
			},
      reset(){
        this.$message.success('触发重置方法');
				
      },
      onSubmit(){
        this.$message.success('触发查询方法')
      },
			reloadPage() {
			 
			}
    },
		computed: {
		  
		}
  }

</script>
<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
